package com.android.support.lib.universal.load;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.support.lib.universal.R;
import com.android.support.lib.universal.base.BaseEntity;
import com.android.support.lib.universal.util.Utilapk;
import com.android.support.lib.universal.util.Utilfile;
import com.lidroid.xutils.http.HttpHandler;

/**
 * 下载 实体类
 * 
 * @author 彭治铭
 *
 */
public class Load extends BaseEntity implements OnClickListener {
	LoadUtil loadUtil = new LoadUtil();
	// 计算当前下载速度
	private long s = 0;
	private int model = LoadState.NO;

	/**
	 * 按钮模式，以State类参数为准
	 */
	public void setModel(int model) {
		this.model = model;
	}

	public int state = LoadState.LINEUP;

	/**
	 * 状态，以State类参数为准
	 */
	public void setState(int state) {
		this.state = state;
		if (this.txtState != null) {
			this.txtState.setText(getState());
		}
		if (btnLoad != null) {
			if (model == LoadState.TEXT) {
				// 文字
				switch (state) {
				case LoadState.DOWNLOAD:
					// 下载中
					btnLoad.setText("暂停");
					break;
				case LoadState.PAUSE:
					// 已暂停
					btnLoad.setText("继续");
					break;
				// 失败，完成
				case LoadState.FAILURE:
				case LoadState.COMPLETE:
					btnLoad.setText("下载");
					break;
				}

			}
			if (model == LoadState.IMG) {
				// 图片
				switch (state) {
				case LoadState.DOWNLOAD:
					// 下载中
					btnLoad.setBackgroundResource(R.drawable.lib_btn_load_stop);
					break;
				case LoadState.FAILURE:
				case LoadState.COMPLETE:
				case LoadState.PAUSE:
					// 已暂停
					btnLoad.setBackgroundResource(R.drawable.lib_btn_load_play);
					break;
				}
			}
		}
		// 完成
		if (state == LoadState.COMPLETE) {
			Utilapk utilapk = new Utilapk();
			packageName = utilapk.getPackageName(path);
			utilapk = null;
			// 清除线程
			this.handler.cancel();
			// 应用卸载安装监听
			BroadcastReceiver InstalledReceiver = new BroadcastReceiver() {

				@Override
				public void onReceive(Context context, Intent intent) {
					// TODO Auto-generated method stub
					String action = intent.getAction();
					String packName = intent.getDataString();// 安装包名
					if (action.equals("android.intent.action.PACKAGE_ADDED")
							|| action
									.equals("android.intent.action.PACKAGE_REPLACED")
							|| action
									.equals("android.intent.action.PACKAGE_REMOVED")) {
						// 安装，卸载，重新安装（其实重新安装不起作用，重新安装被当做卸载处理了。）
						if (packName.equals("package:" + packageName)
								|| packName.equals(packageName)) {
							if (tatal == null) {
								try {
									Utilfile utilfile = new Utilfile();
									tatal = utilfile.getFileSize(path);
									utilfile = null;
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
							Utilfile utilfile = new Utilfile();
							// 删除安装包
							utilfile.delFile(path, null, null);
							utilfile = null;
							if (!tatal.equals("0.0B")) {
								Toast.makeText(
										context,
										name + "安装包已经删除，为你节约了" + tatal
												+ "的空间大小", 2000).show();
							}
							context.unregisterReceiver(this);// 注销掉广播 }
						}
					}

				}

			};
			// 注册广播-卸载安装监听
			IntentFilter filter = new IntentFilter();
			filter.addAction("android.intent.action.PACKAGE_ADDED");// 安装
			filter.addAction("android.intent.action.PACKAGE_REMOVED");// 卸载
			filter.addAction("android.intent.action.PACKAGE_REPLACED");// 覆盖安装,等价于卸载。
			filter.addDataScheme("package");
			context.registerReceiver(InstalledReceiver, filter);
			// 安装
			Utilapk utilapk1 = new Utilapk();
			Utilfile utilfile = new Utilfile();
			utilapk1.getExe(utilfile.getFile(path, null, null));
			utilapk1 = null;
			utilfile = null;
		}
		// 失败
		if (state == LoadState.FAILURE) {
			// 清除线程
			this.handler.cancel();
		}
		if (uiHander != null) {
			// 发送消息，更新UI界面
			Message msg = new Message();
			msg.what = state;// 标识
			msg.getData().putString("id", id);
			uiHander.sendMessage(msg);// 更新UI界面
		}
	}

	/**
	 * 以文字形式显示当前的状态
	 * 
	 * @return
	 */
	public String getState() {
		return LoadState.strState[state];
	}

	private Context context;
	// 下载链接
	private String url;
	// 文件下载完整路径，包括文件名及后缀名
	private String path;
	// 文件名，包括后缀
	private String fileName;
	// 文件名，无后缀名
	private String name;
	// 包名
	private String packageName;
	// 下载文件总大小，单位是字节
	private long byteTotal;
	// 当前文件下载大小，单位是字节
	private long byteCurrent;
	// 文件总大小
	private String tatal;
	// 当前下载大小
	private String current;
	// 当前进度
	private String progress;
	// 当前下载速度
	private String speed;
	// 按钮(继续/暂停),可为null
	private Button btnLoad;
	// 状态文本框
	private TextView txtState;
	// 当前下载大小,文本框（可为null）
	private TextView txtCurrent;
	// 总大小,文本框（可为null）
	private TextView txtTotal;
	// 进度文本框（可为null）
	private TextView txtProgress;
	// 下载速度,文本框（可为null）
	private TextView txtSpeed;
	// xutil的下载框架类
	private HttpHandler handler;
	// 用于更行UI界面
	private Handler uiHander;
	// 进度条（可为null）
	private ProgressBar progressBar;

	/**
	 * 构造方法，没有赋值HttpHandler对象，需要单独赋值
	 * 
	 * @param context
	 *            上下文
	 * @param id
	 *            唯一标示(虽然是字符串类型，但是必须是纯数字，以便转化为int类型)
	 * @param url
	 *            下载url
	 * @param path
	 *            存储路径
	 * @param fileName
	 *            文件名，包括后缀名
	 */
	public Load(Context context, String id, String url, String path,
			String fileName) {
		super();
		this.context = context;
		this.id = id;
		this.url = url;
		this.path = path;
		this.fileName = fileName;
		Utilfile utilfile = new Utilfile();
		this.name = utilfile.getName(fileName);
		utilfile = null;
	}

	/**
	 * * 更新控件
	 * 
	 * @param txtState
	 *            下载状态
	 * @param txtCurrent
	 *            当前下载大小,文本框（可为null）
	 * @param txtTotal
	 *            总大小,文本框（可为null）
	 * @param txtProgress
	 *            进度,文本框（可为null）
	 * @param txtSpeed
	 *            下载速度,文本框（可为null）
	 * 
	 * @param btnLoad
	 *            下载控制按钮(继续/暂停),可为null
	 * @param model
	 *            按钮模式，以State类参数为准
	 * @param uiHander
	 *            用于更新UI界面
	 * @param progressBar
	 *            进度条
	 */
	public void setTxt(TextView txtState, TextView txtCurrent,
			TextView txtTotal, TextView txtProgress, TextView txtSpeed,
			Button btnLoad, int model, Handler uiHander, ProgressBar progressBar) {
		this.txtCurrent = txtCurrent;
		this.txtTotal = txtTotal;
		this.txtProgress = txtProgress;
		this.txtSpeed = txtSpeed;
		this.btnLoad = btnLoad;
		this.txtState = txtState;
		this.model = model;
		if (this.btnLoad != null) {
			this.btnLoad.setOnClickListener(this);
		}
		this.progressBar = progressBar;
		this.uiHander = uiHander;
	}

	/**
	 * 停止下载
	 */
	public void cancel() {
		this.handler.cancel();
		setState(LoadState.PAUSE);
	}

	/**
	 * 按钮点击事件，支持断点续传(下载，暂停轮回替换)
	 */
	public void loadListener() {

		switch (state) {
		// 下载中
		case LoadState.DOWNLOAD:
			// 开始暂停
			cancel();
			break;
		// 排队等待中
		case LoadState.LINEUP:
			// 什么也不做，静静的等待
			break;
		// 非下载中(暂停，完成，失败)
		default:
			// 继续下载
			loadUtil.loadFile(context, id, url, fileName, txtState, txtCurrent,
					txtTotal, txtProgress, txtSpeed, btnLoad, model, uiHander,
					progressBar);
			break;
		}

	}

	/**
	 * 是否需要重新下载
	 * 
	 * @return true(需要重新下载)， false(不需要重新下载)
	 */
	public Boolean reLoad() {
		Boolean bool = true;
		switch (state) {
		// 下载中
		case LoadState.DOWNLOAD:
			// 开始暂停
			bool = false;
			break;
		// 排队等待中
		case LoadState.LINEUP:
			// 什么也不做，静静的等待
			bool = false;
			break;
		// 非下载中(暂停，完成，失败)
		default:
			// 继续下载
			bool = true;
			break;
		}
		return bool;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		loadListener();
	}

	public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public long getByteTotal() {
		return byteTotal;
	}

	public void setByteTotal(long byteTotal) {
		this.byteTotal = byteTotal;
	}

	public long getByteCurrent() {
		return byteCurrent;
	}

	public void setByteCurrent(long byteCurrent) {
		this.byteCurrent = byteCurrent;
	}

	public String getTatal() {
		return tatal;
	}

	public void setTatal(String tatal) {
		this.tatal = tatal;
	}

	public String getCurrent() {
		return current;
	}

	public void setCurrent(String current) {
		this.current = current;
	}

	public String getProgress() {
		return progress;
	}

	public void setProgress(String progress) {
		this.progress = progress;
	}

	public String getSpeed() {
		return speed;
	}

	public void setSpeed(String speed) {
		this.speed = speed;
	}

	public long getS() {
		return s;
	}

	public void setS(long s) {
		this.s = s;
	}

	public Button getBtnLoad() {
		return btnLoad;
	}

	public void setBtnLoad(Button btnLoad) {
		this.btnLoad = btnLoad;
	}

	public TextView getTxtState() {
		return txtState;
	}

	public void setTxtState(TextView txtState) {
		this.txtState = txtState;
	}

	public TextView getTxtCurrent() {
		return txtCurrent;
	}

	public void setTxtCurrent(TextView txtCurrent) {
		this.txtCurrent = txtCurrent;
	}

	public TextView getTxtTotal() {
		return txtTotal;
	}

	public void setTxtTotal(TextView txtTotal) {
		this.txtTotal = txtTotal;
	}

	public TextView getTxtProgress() {
		return txtProgress;
	}

	public void setTxtProgress(TextView txtProgress) {
		this.txtProgress = txtProgress;
	}

	public TextView getTxtSpeed() {
		return txtSpeed;
	}

	public void setTxtSpeed(TextView txtSpeed) {
		this.txtSpeed = txtSpeed;
	}

	public HttpHandler getHandler() {
		return handler;
	}

	public void setHandler(HttpHandler handler) {
		this.handler = handler;
	}

	public int getModel() {
		return model;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Handler getUiHander() {
		return uiHander;
	}

	public void setUiHander(Handler uiHander) {
		this.uiHander = uiHander;
	}

	public ProgressBar getProgressBar() {
		return progressBar;
	}

	public void setProgressBar(ProgressBar progressBar) {
		this.progressBar = progressBar;
	}

	public String getPackageName() {
		return packageName;
	}

	public void setPackageName(String packageName) {
		this.packageName = packageName;
	}

}
